import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';
import { useAuthStore } from '@/store/modules/auth';

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/dashboard',
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    meta: { title: '登录', layout: 'auth', requiresAuth: false },
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/auth/Register.vue'),
    meta: { title: '注册', layout: 'auth', requiresAuth: false },
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/Dashboard.vue'),
    meta: { title: '首页概览', requiresAuth: true },
  },
  {
    path: '/questions',
    name: 'Questions',
    component: () => import('@/views/questions/QuestionCenter.vue'),
    meta: { title: '智能问答', requiresAuth: true },
  },
  {
    path: '/images',
    name: 'Images',
    component: () => import('@/views/images/ImageAnalysis.vue'),
    meta: { title: '影像分析', requiresAuth: true },
  },
  {
    path: '/history',
    name: 'History',
    component: () => import('@/views/history/HistoryCenter.vue'),
    meta: { title: '健康档案', requiresAuth: true },
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/dashboard',
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior: () => ({ top: 0 }),
});

router.afterEach((to) => {
  if (to.meta?.title) {
    document.title = `${to.meta.title} · TCM Smart Health Assistant`;
  }
});

export function setupRouterGuards() {
  router.beforeEach(async (to) => {
    const authStore = useAuthStore();

    if (!authStore.initialized) {
      await authStore.initialize();
    }

    const requiresAuth = to.meta.requiresAuth !== false;
    const isLoggedIn = authStore.isAuthenticated && Boolean(authStore.user);

    if (requiresAuth && !isLoggedIn) {
      return { path: '/login', query: { redirect: to.fullPath } };
    }

    if ((to.path === '/login' || to.path === '/register') && isLoggedIn) {
      return { path: '/dashboard' };
    }

    return true;
  });
}

export default router;

